import { defineStore } from 'pinia'
import { getCommentsByPostIdUsingGet } from '../../../Api/pinglunmokuai.js'
import { showDialog } from 'vant'
import {Comment} from "../../types/YRCG/TeachingPostComment";

/**
 * 教学帖子评论存储模块
 * 负责管理教学帖子评论的全局状态
 */
export const useTeachingPostCommentStore = defineStore('teachingPostComment', {
    // 持久化配置
    persist: {
        storage: localStorage,
        paths: ['comments', 'replyingTo']
    },
    state: () => ({
        comments: [] as Comment[],
        loading: false,
        error: null as string | null,
        replyingTo: null as number | null
    }),

    actions: {
        /**
         * 获取帖子的评论
         * @param postId - 帖子ID
         */
        async fetchComments(postId: number) {
            this.loading = true
            this.error = null

            try {
                const response = await getCommentsByPostIdUsingGet({ postId })

                if (response.data.code === 0) {
                    this.comments = this.transformComments(response.data.data)
                } else {
                    throw new Error(response.data.message || '获取评论失败')
                }
            } catch (error) {
                console.error('获取评论失败:', error)
                this.error = error.message || '获取评论失败'
                showDialog({
                    message: this.error
                })
            } finally {
                this.loading = false
            }
        },

        /**
         * 转换评论数据为树形结构
         * @param comments - 扁平评论列表
         */
        transformComments(comments: Comment[]): Comment[] {
            const commentMap = new Map<number, Comment>()
            const rootComments: Comment[] = []

            // 首先创建所有评论的映射
            comments.forEach(comment => {
                commentMap.set(comment.id, { ...comment, children: [] })
            })

            // 构建树形结构
            comments.forEach(comment => {
                const node = commentMap.get(comment.id)
                if (comment.parentId === 0) {
                    rootComments.push(node!)
                } else {
                    const parent = commentMap.get(comment.parentId)
                    parent?.children?.push(node!)
                }
            })

            return rootComments
        },

        /**
         * 添加评论
         * @param newComment - 新评论对象
         */
        async addComment(newComment: Omit<Comment, 'id' | 'createTime'>) {
            this.loading = true
            try {
                // 这里调用API添加评论
                // const response = await addCommentApi(newComment)
                // this.comments = this.transformComments([...this.flattenComments(), response.data])
            } catch (error) {
                console.error('添加评论失败:', error)
                this.error = error.message || '添加评论失败'
                showDialog({
                    message: this.error
                })
            } finally {
                this.loading = false
            }
        },

        /**
         * 将树形评论展平
         */
        flattenComments(): Comment[] {
            const result: Comment[] = []

            function flatten(comment: Comment) {
                result.push(comment)
                comment.children?.forEach(flatten)
            }

            this.comments.forEach(flatten)
            return result
        },

        /**
         * 设置当前回复的评论
         * @param commentId - 评论ID
         */
        setReplyingTo(commentId: number | null) {
            this.replyingTo = commentId
        },

        /**
         * 删除评论
         * @param commentId - 评论ID
         */
        async deleteComment(commentId: number) {
            this.loading = true
            try {
                // 这里调用API删除评论
                // await deleteCommentApi(commentId)
                // this.comments = this.transformComments(this.flattenComments().filter(c => c.id !== commentId))
            } catch (error) {
                console.error('删除评论失败:', error)
                this.error = error.message || '删除评论失败'
                showDialog({
                    message: this.error
                })
            } finally {
                this.loading = false
            }
        }
    },

    getters: {
        /**
         * 获取主评论列表（非回复评论）
         */
        mainComments(state): Comment[] {
            return state.comments
        },

        /**
         * 获取指定评论的回复
         * @param commentId - 评论ID
         */
        repliesToComment: (state) => (commentId: number) => {
            const comment = state.comments.find(c => c.id === commentId)
            return comment?.children || []
        },

        /**
         * 获取当前回复的评论信息
         */
        replyingToComment(state): Comment | null {
            if (!state.replyingTo) return null
            return this.flattenComments().find(c => c.id === state.replyingTo) || null
        }
    }
})
